package com.iking.toolkit.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.iking.toolkit.model.Msg;
import com.iking.toolkit.util.SysUtil;
import com.iking.toolkit.system.dao.DictionaryItemsMapper;
import com.iking.toolkit.system.dao.DictionaryTypeMapper;
import com.iking.toolkit.system.model.http.HttpDictionaryTypeSelectReq;
import com.iking.toolkit.system.model.model.DictionaryItems;
import com.iking.toolkit.system.model.model.DictionaryType;
import com.iking.toolkit.system.service.DictionaryTypeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * dictionary_type（数据字典类型） ServiceImpl
 *
 * @author user
 * @since 2022-10-09
 */
@Slf4j
@Service
public class DictionaryTypeServiceImpl implements DictionaryTypeService {

    /**
     * 数据字典类型
     */
    @Autowired
    private DictionaryTypeMapper dictionaryTypeMapper;
    /**
     * 数据字典内容
     */
    @Autowired
    private DictionaryItemsMapper dictionaryItemsMapper;

    /**
     * @Description: 查询全部数据字典类型
     * @Param: [req]
     * @return: com.iking.common.model.Msg
     * @Author: wk
     * @Date: 7/2/2020 上午9:49
     */
    @Override
    public Msg searchDictionaryType(HttpDictionaryTypeSelectReq req) {
        try {
            List<DictionaryType> listDictionaryType = dictionaryTypeMapper.searchDictionaryType(req);
            return Msg.sucess(listDictionaryType);
        } catch (Exception e) {
            log.error("查询数据字典类型异常 :" + e);
            return Msg.fail("查询数据字典类型异常");
        }
    }

    /**
     * @Description: 删除数据字典类型
     * @Param: [id]
     * @return: com.iking.common.model.Msg
     * @Author: wk
     * @Date: 7/2/2020 上午9:54
     */
    @Override
    public Msg deleteByPrimaryKey(String id) {
        try {
            DictionaryType dictionaryType = dictionaryTypeMapper.selectByPrimaryKey(id);
            if (dictionaryType == null) {
                return Msg.fail("数据字典类型不存在");
            }
            if (dictionaryType.getIsDelete()) {
                return Msg.fail("数据字典类型已删除！");
            }
            if (dictionaryType.getIsSysDefault()) {
                return Msg.fail("系统预设类型不能删除");
            }
            // 数据字典内容校验
            List<DictionaryItems> listDictionary = dictionaryItemsMapper.selectByTypeId(id);
            if (listDictionary != null && listDictionary.size() > 0) {
                return Msg.fail("此类型下有内容数据，不能删除！");
            }
            dictionaryType.setIsDelete(true);
            int count = dictionaryTypeMapper.updateByPrimaryKeySelective(dictionaryType);
            if (count < 1) {
                return Msg.fail("删除数据字典类型失败");
            }
            return Msg.sucess("删除成功");
        } catch (Exception e) {
            log.error("删除数据字典类型异常 :" + e);
            return Msg.fail("删除数据字典类型异常");
        }
    }

    /**
     * @Description: 修改数据字典类型
     * @Param: [req]
     * @return: com.iking.common.model.Msg
     * @Author: wk
     * @Date: 7/2/2020 上午9:53
     */
    @Override
    public Msg update(DictionaryType req) {
        try {
            // 数据字典类型存在性校验
            DictionaryType model = dictionaryTypeMapper.selectByPrimaryKey(req.getDictionaryTypeId());
            if (model == null) {
                return Msg.fail("数据字典类型不存在");
            }
            if (model.getIsDelete()) {
                return Msg.fail("数据字典类型已删除！");
            }
            if (model.getIsSysDefault()) {
                return Msg.fail("系统预设类型不能修改");
            }
            List<DictionaryType> listfPymUpdate = null;
            List<DictionaryType> listfNameUpdate = null;
            // 修改了拼音码后校验其存在性
            if (!model.getTypePym().equals(req.getTypePym())) {
                listfPymUpdate = dictionaryTypeMapper.searchByPymUpdate(req);
            }
            // 修改了拼音码后校验其存在性
            if (!model.getDictionaryTypeName().equals(req.getDictionaryTypeName())) {
                listfNameUpdate = dictionaryTypeMapper.searchByNameUpdate(req);
            }
            // 拼音码已存在
            if (listfPymUpdate != null && listfPymUpdate.size() > 0) {
                return Msg.fail("参数" + req.getTypePym() + "已存在！");
            }
            // 名称已存在
            if (listfNameUpdate != null && listfNameUpdate.size() > 0) {
                return Msg.fail("名称" + req.getDictionaryTypeName() + "已存在！");
            }
            model.setTypePym(req.getTypePym());
            model.setDictionaryTypeName(req.getDictionaryTypeName());
            // 排序禁止修改
            model.setSort(null);
            model.setDescription(req.getDescription());
            model.setIsSysDefault(req.getIsSysDefault());
            model.setIsDelete(req.getIsDelete());
            model.setIsEnable(req.getIsEnable());
            model.setUpdateTime(new Date());
            int count = dictionaryTypeMapper.updateByPrimaryKeySelective(model);
            if (count < 1) {
                return Msg.fail("修改数据字典类型失败");
            }
            return Msg.sucess("修改成功");
        } catch (Exception e) {
            log.error("修改数据字典类型异常 :" + e);
            return Msg.fail("修改数据字典类型异常");
        }
    }

    /**
     * @Description: 新增数据字典类型
     * @Param: [req]
     * @return: com.iking.common.model.Msg
     * @Author: wk
     * @Date: 7/2/2020 上午9:52
     */
    @Override
    public Msg insert(DictionaryType dictionaryType) {
        try {
            // 判断拼音码是否存在
            List<DictionaryType> listPymInsert = dictionaryTypeMapper.searchByPymInsert(dictionaryType);
            // 判断名称是否存在
            List<DictionaryType> listNameInsert = dictionaryTypeMapper.searchByNameInsert(dictionaryType);
            // 拼音码已存在
            if (listPymInsert != null && listPymInsert.size() > 0) {
                return Msg.fail("参数" + dictionaryType.getTypePym() + "已存在！");
            }
            // 名称已存在
            if (listNameInsert != null && listNameInsert.size() > 0) {
                return Msg.fail("名称" + dictionaryType.getDictionaryTypeName() + "已存在！");
            }

            dictionaryType.setDictionaryTypeId(SysUtil.getUUID());
            dictionaryType.setCreateTime(new Date());
            dictionaryType.setIsEnable(true);
            dictionaryType.setUpdateTime(new Date());
            dictionaryType.setIsDelete(false);
            int sort = dictionaryTypeMapper.MaxSort();
            sort++;
            dictionaryType.setSort(sort);
            int count = dictionaryTypeMapper.insert(dictionaryType);
            if (count < 1) {
                return Msg.fail("新增数据字典类型失败");
            }
            return Msg.sucess("新增成功");
        } catch (Exception e) {
            log.error("新增数据字典类型异常 :" + e);
            return Msg.fail("新增数据字典类型异常");
        }
    }

    /**
     * 根据字典项编号批量查询字典内容列表
     *
     * @param dictNoList
     * @return
     */
    @Override
    public Msg<Map<String, List<DictionaryItems>>> selectBatchDictItemsByDictTypeNo(List<String> dictNoList) {
        try {
            //1.校验
            dictNoList = dictNoList.stream().distinct().collect(Collectors.toList());
            if (CollUtil.isEmpty(dictNoList)) {
                return Msg.fail("元数据字典不存在");
            }
            LambdaQueryWrapper<DictionaryType> dictTypeWrapper = new LambdaQueryWrapper<>();
            dictTypeWrapper.in(DictionaryType::getTypePym, dictNoList);
            List<DictionaryType> metadataDictTypes = dictionaryTypeMapper.selectList(dictTypeWrapper);
            if (CollUtil.isEmpty(metadataDictTypes)) {
                return Msg.fail("数据字典不存在");
            }
            //2.查询
            List<String> dictTypeIdList = metadataDictTypes.stream().map(DictionaryType::getDictionaryTypeId)
                    .collect(Collectors.toList());
            LambdaQueryWrapper<DictionaryItems> dictItemWrapper = new LambdaQueryWrapper<>();
            dictItemWrapper.in(DictionaryItems::getDictionaryTypeId, dictTypeIdList);
            List<DictionaryItems> metadataDictItems = dictionaryItemsMapper.selectList(dictItemWrapper);

            Map<String, List<DictionaryItems>> resultMap = new HashMap<>(16);
            //3.组装
            Map<String, List<DictionaryItems>> dictItemMap = metadataDictItems.stream()
                    .collect(Collectors.groupingBy(DictionaryItems::getDictionaryTypeId));
            metadataDictTypes.forEach(e -> resultMap.put(e.getTypePym(), dictItemMap.get(e.getDictionaryTypeId())));
            return Msg.sucess(resultMap);
        } catch (Exception e) {
            log.error("根据字典项编号批量查询字典内容列表失败==>requestParams={}", JSONUtil.toJsonStr(dictNoList), e);
            return Msg.fail("根据字典项编号批量查询字典内容列表失败");
        }
    }

}
